package com.itboye.lottery.activity.user;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.bylibrary.widget.glide.GlideUtil;
import com.itboye.lottery.base.BaseActivity;
import com.itboye.lottery.R;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.annotions.IsNeedClick;
import com.itboye.lottery.presenter.UserPresenter;
import com.itboye.lottery.retrofit.ResponseCallback;
import com.itboye.lottery.utils.Const;
import com.itboye.lottery.utils.GlideLoader;
import com.itboye.lottery.utils.PermissionListener;
import com.itboye.lottery.utils.SPUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.itboye.lottery.utils.ImageCompress.compress;
import static com.itboye.lottery.utils.SPUtils.getSp;

public class UserDataActivity extends BaseActivity implements ResponseCallback {

    RelativeLayout rl_nickname, rl_phone, rl_head;
    @IsNeedClick
    ImageView iv_user_head;
    @IsNeedClick
    TextView tv_nickname, tv_phone;
    UserPresenter userPresenter;
    private List<String> photoList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_data;
    }

    private String[] PERMISSIONS = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    protected void initData() {
        setTitle("个人资料");
        userPresenter = new UserPresenter(this);
        checkMyPermission();
        initGallery();
    }

    boolean isGranted = true;

    private boolean checkMyPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            requestRunPermisssion(PERMISSIONS, new PermissionListener() {
                @Override
                public void onGranted() {
                    isGranted = true;
                }

                @Override
                public void onDenied(List<String> deniedPermission) {
                    openAppDetails("检测到您拒绝了读取存储的权限,请手动打开哦!");
                    isGranted = false;
                }
            });
        }
        return isGranted;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_nickname:
            case R.id.tv_nickname:
                //修改昵称
                startActivity(new Intent(this, EditNicknameActivity.class));
                break;
            case R.id.rl_phone:
            case R.id.tv_phone:
                //修改绑定的手机
                if (getSp(Const.Companion.getPHONE()) == null || "".equals(getSp(Const.Companion.getPHONE()))) {
                    //未綁定手机 绑定手机
                    startActivity(new Intent(this, EditPhoneActivity.class).putExtra("type", 5));
                } else {
                    //否则修改绑定手机
                    startActivity(new Intent(this, EditPhoneActivity.class).putExtra("type", 6));
                }
                break;
            case R.id.rl_head:
            case R.id.iv_user_head:
                if (checkMyPermission()) {
                    openLibrary();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUserData();
    }

    private void setUserData() {
        GlideUtil.displayForCircle(this, getSp(Const.Companion.getUSER_HEAD()) + "", R.mipmap.head_default, iv_user_head);
        tv_nickname.setText(getSp(Const.Companion.getNICKNAME()) + "");
        tv_phone.setText(getSp(Const.Companion.getPHONE()) + "");
    }

    private GalleryConfig galleryConfig;
    private IHandlerCallBack iHandlerCallBack;

    //选择图片
    private void openLibrary() {
        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider(getPackageName() + ".fileprovider")   // provider(必填)
                .pathList(photoList)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();
//        ImageConfig imageConfig
//                = new ImageConfig.Builder(new GlideLoader())
//                .steepToolBarColor(getResources().getColor(R.color.blue))
//                .titleBgColor(getResources().getColor(R.color.blue))
//                .titleSubmitTextColor(getResources().getColor(R.color.white))
//                .titleTextColor(getResources().getColor(R.color.white))
//                .provider(getPackageName() + ".fileprovider")   // provider(必填)
//                // (截图默认配置：关闭    比例 1：1    输出分辨率  500*500)
////                .crop(2, 1, 1000, 500)
//                // 开启单选   （默认为多选）
//                .singleSelect()
//                // 开启拍照功能 （默认关闭）
//                .showCamera()
//                // 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
//                .filePath("/ImageSelector/Pictures")
//                .build();
//        ImageSelector.open(this, imageConfig);   // 开启图片选择器
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
    }

    private void initGallery() {
        iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(List<String> photoList) {
                UserDataActivity.this.photoList = photoList;
                if (photoList != null) {
                    if (photoList.size() > 0) {
                        showDialog("正在上传中,请稍后");
                        String path = compress(photoList.get(0));
                        File file = new File(path);
                        GlideUtil.display(UserDataActivity.this, photoList.get(0), iv_user_head);
                        //准备上传
                        userPresenter.uploadAvatar(file);
                    }
                } else {
                    UserDataActivity.this.photoList = new ArrayList<>();
                }
            }


            @Override
            public void onCancel() {
            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onError() {
            }
        };

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
//            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
//
//        }
//        else if (requestCode == getPERMISSION_ACTIVITY_REQUESTCODE()) {
//            checkMyPermission();
//        }
    }

    @Override
    public void success(@NotNull Object o, @NotNull String requestSuccessType) {
        if (requestSuccessType == userPresenter.uploadAvatar_SUCCESS) {
            ByAlert.alert("上传成功");
            SPUtils.put(this, null, Const.Companion.getUSER_HEAD(), o);
            setUserData();
        }
        dissDialog();
    }

    @Override
    public void fail(int code, @NotNull Object msg, @NotNull String requestErrorType) {
        dissDialog();
        ByAlert.alert(msg);

    }
}
